# encoding=utf8
# author: allen
# create_time: 2024/5/7 11:16
# file: contract.py
from api.datas.data_api import get_touzi_list_by_task, get_user, update_user, update_task
from loguru import logger


class ReturnContract:
    # 失败退款
    def __init__(self, change_status, task_dict):
        self.task_dict = task_dict
        self.condition = change_status == '众筹失败' and task_dict.get('status') != '众筹失败'
        self.action = self.return_money

    def return_money(self):
        m_list = get_touzi_list_by_task(self.task_dict.get('task_id'))
        logger.info('ReturnContract action => count: {}'.format(len(m_list)))
        for m in m_list:
            money = m['money']
            user = get_user({'user_id': m['user_id']})
            if not user:
                continue
            else:
                inc = user[0].get('money', 0) + int(money)
                logger.info(
                    'ReturnContract action => user_id:{} {} => {}'.format(m['user_id'], user[0].get('money', 0), inc))
                update_user(m['user_id'], {'money': inc})
        return True

    def execute(self):
        if self.condition:
            logger.info("ReturnContract => 条件满足，执行合约")
            return self.action()
        else:
            logger.info("ReturnContract => 条件不满足，无法执行合约")
            return False


class DeliverContract:
    # 成功放款
    def __init__(self, task_dict, deliver_lcb_index):
        self.task_dict = task_dict
        self.deliver_lcb_index = deliver_lcb_index
        self.condition = task_dict['inputItems'][deliver_lcb_index].get('get_price') >= \
                         task_dict['inputItems'][deliver_lcb_index].get('price') and \
                         task_dict['inputItems'][deliver_lcb_index].get('is_push_money', 0) != 1
        self.action = self.push_money

    def push_money(self):
        user = get_user({'user_id': self.task_dict['user_id']})
        money = self.task_dict['inputItems'][self.deliver_lcb_index].get('get_price')
        if not user:
            return False

        inc = user[0].get('money', 0) + int(money)
        logger.info('DeliverContract action => user_id:{} {} => {}'.
                    format(self.task_dict['user_id'], user[0].get('money', 0), inc))

        update_task(self.task_dict['task_id'], {'inputItems.{}.is_push_money'.format(self.deliver_lcb_index): 1, })
        update_user(self.task_dict['user_id'], {'money': inc})
        return True

    def execute(self):
        if self.condition:
            logger.info("DeliverContract => 条件满足，执行合约")
            return self.action()
        else:
            logger.info("DeliverContract => 条件不满足，无法执行合约")
            return False


class TestContract:
    def __init__(self):
        self.condition = lambda x: x > 10
        self.action = lambda x: x*2

    def execute(self, *args, **kwargs):
        if self.condition(*args, **kwargs):
            res = self.action(*args, **kwargs)
            print(res)
        else:
            print("条件不满足，无法执行合约")


if __name__ == '__main__':
    contract = TestContract()
    contract.execute(5)
    contract.execute(15)

    rc = ReturnContract('众筹失败1', {
        "name": "撒发放打底衫",
        "price": "1000",
        "inputItems": [
            {
                "price": "500",
                "text": "500",
                "get_price": 100,
                "status": 1
            },
            {
                "price": "500",
                "text": "500"
            }
        ],
        "task_desc": "阿萨德会计法宽带了",
        "reward_type": "股权",
        "reward_desc": "阿萨德发呆思考福建",
        "user_id": "b4ec6b98-022b-11ef-8edf-525400486c77",
        "status": "正在进行",
        "task_id": "67248cee-0a0d-11ef-8b73-525400486c77",
        "create_time": "2024-05-04 19:56:55",
        "update_time": "2024-05-04 19:56:55"
    })
    rc.execute()
